// pages/clock/clock.js
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js')
var qqmapsdk = new QQMapWX({
  key: 'VZGBZ-YIHCQ-SR55P-GNN73-DNDYF-CGF2O'
});
var times = require('../../utils/time.js')
const {
  imgConfig,
  config
} = require('../../utils/config.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

    todayClick: false,
    imgUrl: `${imgConfig}`,
    statusBarHeight: app.globalData.statusBarHeight,
    flag: [5, 0, 0],
    startext: ['非常满意', '', '', ],
    starsBox: [1, 2, 3, 4, 5],
    teaIndex: '',
    num: 5,
    remarks: '',
    time: times.formatTime(new Date()),
    courseChapterList: '',
    chapterList: '',
    chapterIndex: app.globalData.chapterIndex,
    courseIndex: app.globalData.courseIndex,
    courseId: '',
    chapterId: ''

  },
 
  back: function () {
    wx.navigateBack({});
  },
  goLcaClock(){
    console.log(app.globalData.clockStatus)
    if (app.globalData.clockStatus) {
      wx.showToast({
        title: '请完成下课打卡!',
        icon: 'none'
      })
      return
    }
    if (this.data.chapterIndex === undefined || this.data.courseIndex === undefined) {
      wx.showToast({
        title: '请选择课程章节!',
        icon: 'none'
      })
      return
    }
    app.globalData.courseId = this.data.courseId
    app.globalData.chapterId = this.data.chapterId
    wx.navigateTo({
      url: '/pages/lcaClock/lcaClock?status=0',
    })
  },
  //remarks输入双向数据绑定
  remarksInput: function (e) {
    this.setData({
      remarks: e.detail.value
    })
  },
  /**
   * 星级评分 获取当前选中的是几颗星 num
   */
  changePic: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.index;
    var num = e.currentTarget.dataset.no;
    console.log(num);
    var a = 'flag[' + index + ']';
    var b = 'startext[' + index + ']';
    var that = this;
    if (num == 1) {
      that.setData({
        num: num,
        [a]: 1,
        [b]: '非常不满意'
      });
    } else if (num == 2) {
      that.setData({
        num: num,
        [a]: 2,
        [b]: '不满意'
      });
    } else if (num == 3) {
      that.setData({
        num: num,
        [a]: 3,
        [b]: '一般'
      });
    } else if (num == 4) {
      that.setData({
        num: num,
        [a]: 4,
        [b]: '满意'
      });
    } else if (num == 5) {
      that.setData({
        num: num,
        [a]: 5,
        [b]: '非常满意'
      });
    }
  },
  /**
   * 打卡 发送请求
   */
  punchTheClock: function () {
    var that = this
    if (this.data.chapterIndex === "" || this.data.courseIndex === "") {
      wx.showToast({
        title: '请选择课程章节!',
        icon: 'none'
      })
      return
    }
    console.log(app.globalData.clockStatus)
    if (!app.globalData.clockStatus) {
      wx.showToast({
        title: '请完成下课打卡!',
        icon: 'none'
      })
      return
    }
    var studentInfo = app.globalData.userInfo
    //上课打卡
    var score = null
    var clockStatus = 0
    //打卡确认
    wx.showModal({
      title: '提示',
      content: '是否确认打卡?',
      success(res) {
        console.log(clockStatus)
        if (res.confirm) {
          wx.request({
            url: `${config}/wechat/wxclock/saveClock`,
            method: 'post',
            data: {
              stuId: studentInfo.id,
              courseId: that.data.courseId,
              chapterId: that.data.chapterId,
              clockStatus: clockStatus
            },
            success(resp) {
              console.log(resp)

              //打卡状态
              if (resp.data.code == 0) {
                wx.showToast({
                  title: '打卡成功',
                  duration: 1000
                })
                setTimeout(function () {
                  wx.switchTab({
                    url: '/pages/my/my',
                  })
                }, 1000)
              }
            }
          }) //请求结束
        } else if (res.cancel) {
          wx.showToast({
            title: '已取消打卡!',
            icon: 'none',
            duration: 1000
          })
        }
      }
    })

  },
  //选择课程 修改索引
  listenerCoursePickerSelected: function (e) {
    //改变index值，通过setData()方法重绘界面
    var that = this
    this.setData({
      courseIndex: e.detail.value,
      chapterList: that.data.courseChapterList[e.detail.value].chapter,
      courseId: that.data.courseChapterList[e.detail.value].id,
      //课程更改 清空章节列表索引
      chapterIndex: ''
    });
    console.log("选取课程Id:", that.data.courseId)
  },
  //选择章节 修改索引
  listenerChapterPickerSelected: function (e) {
    //改变index值，通过setData()方法重绘界面
    var that = this
    this.setData({
      chapterIndex: e.detail.value,
      chapterId: that.data.chapterList[e.detail.value].id
    });
    console.log("选取章节Id:", that.data.chapterId)
  },
  /**
   * 页面当前时间定时器
   */
  timeInterval() {
    //打卡组件  显示当前时间定时器
    setInterval(() => {
      var date = times.formatTime(new Date());
      this.setData({
        time: date,
      })
    }, 1000)
  },
  /**
   * 获取课程、章节信息
   */
  getCourseChapterList() {
    var that = this;
    var studentInfo = app.globalData.userInfo
    //发送获取课程信息的请求
    wx.request({
      url: `${config}/wechat/wxclock/getCourseChapterList`,
      data: {
        majorId: studentInfo.majorId
      },
      success(resp) {
        console.log(resp)
        //课程信息赋值给前台
        that.setData({
          courseChapterList: resp.data.courseChapterList,
        })
        
        //判断是否有打卡记录 没有则不对章节赋值
        if (app.globalData.courseIndex === ''|| app.globalData.courseIndex == undefined || app.globalData.chapterIndex === ''|| app.globalData.chapterIndex == undefined) {
          return
        }
        //通过后台获取的打卡记录 选取对应的章节列表 赋值课程列表索引
        var courseIndex = app.globalData.courseIndex
        var courseLength = that.data.courseChapterList.length
        
        that.setData({
          chapterList: resp.data.courseChapterList[courseIndex].chapter,
        })
        /* 小程序获取数据全部都是异步的 数组必须先存在才能获取长度 */
        var chapterLength = that.data.chapterList.length
        var chapterIndex = app.globalData.chapterIndex
        //通过后台获取打卡记录 自动选取下一节打卡课程
        var status = app.globalData.clockStatus        

        //判断最后一次打卡为下课打卡且章节是最后一个章节 课程不是最后一个课程  章节索引变为0 课程索引加1
        if (chapterIndex + 1 >= chapterLength && courseIndex + 1 < courseLength ) {
          chapterIndex = 0
          courseIndex += 1
        } //章节不是最后一个  章节索引加1 
        else if (chapterIndex + 1 < chapterLength ) {
          chapterIndex += 1
        }
        //章节为最后一章 章节索引为最大值
        if (courseIndex + 1 >= courseLength) {
          courseIndex = courseLength - 1
          //章节 课程都为最后一个 章节索引 课程索引都为最大值
        } else if (courseIndex + 1 > courseLength && chapterIndex + 1 > chapterLength) {
          courseIndex = courseLength - 1
          chapterIndex = chapterLength - 1
        }
        console.log('chapterIndex:', chapterIndex)
        console.log('courseIndex:', courseIndex)
        that.setData({
          chapterList: resp.data.courseChapterList[courseIndex].chapter,
          courseIndex: courseIndex,
          chapterIndex: chapterIndex,
          courseId: resp.data.courseChapterList[courseIndex].id,
          chapterId: resp.data.courseChapterList[courseIndex].chapter[chapterIndex].id
        })
        console.log("课程Id:", that.data.courseId, ",章节Id:", that.data.chapterId)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.timeInterval()
    // this.getLastClock()
    this.getCourseChapterList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.setData({
      avatar: app.globalData.userInfo.photo, //头像
      stuName: app.globalData.userInfo.stuName, //姓名
      phoneNumber: app.globalData.userInfo.stuTel, //手机号
    })
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 获取最新打卡参数
   */
  getLastClock() {
    var that = this
    //Storage中存入新的打卡数据 用于返回后访问打卡页使用
    wx.request({
      url: `${config}/wechat/wxclock/getLastClock`,
      data: {
        stuId: app.globalData.userInfo.id
      },
      success(res) {
        console.log(res)
        if (res.data.clockEntity == null || res.data.clockEntity == undefined) {
          that.data.clockStatus = true
          return
        }
        if(res.data.clockEntity.updateTime == null){
          var clockStatus = false
        }else{
          var clockStatus = true
        }
        var courseId = res.data.clockEntity.courseId
        var chapterId = res.data.clockEntity.chapterId
        var courseChapterList = that.data.courseChapterList
        for (var i = 0; i < courseChapterList.length; i++) {
          if (courseChapterList[i].id == courseId) {
           var courseIndex = i
          }

        }
        that.setData({
          courseIndex: courseIndex
        })
        console.log(courseChapterList[courseIndex])
        console.log(courseIndex)
        var chapterList = courseChapterList[courseIndex].chapter
        for (var i = 0; i < chapterList.length; i++) {
          if (chapterList[i].id == chapterId) {
            var  chapterIndex = i
          }

        }
        that.setData({
          chapterIndex: chapterIndex
        })
        // app.globalData.clockStatus = clockStatus //添加打卡状态 页面显示 上课/下课打卡
        // app.globalData.chapterIndex = that.data.chapterIndex //添加章节列表索引
        // app.globalData.courseIndex = that.data.courseIndex //添加课程列表索引
      }
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})